﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System;
using Tesla.Core;

namespace Tesla.Graphics.Implementation {
    /// <summary>
    /// Abstract class for concrete subclasses to provide the underlying implementation of <see cref="VertexBuffer"/>.
    /// </summary>
    public abstract class VertexBufferImplementation : GraphicsResourceImplementation {
        private VertexDeclaration _vertexDecl;
        private int _vertexCount;
        private ResourceUsage _bufferUsage;

        /// <summary>
        /// Gets the number of vertices contained in this buffer.
        /// </summary>
        public int VertexCount {
            get {
                return _vertexCount;
            }
        }

        /// <summary>
        /// Gets the vertx declaration that describes the type of data contained in
        /// this buffer.
        /// </summary>
        public VertexDeclaration VertexDeclaration {
            get {
                return _vertexDecl;
            }
        }

        /// <summary>
        /// Gets the resource usage of the buffer, either static or dynamic.
        /// </summary>
        public ResourceUsage BufferUsage {
            get {
                return _bufferUsage;
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="VertexBufferImplementation"/>.
        /// </summary>
        /// <param name="vertexDeclaration">The vertex declaration that describes the data.</param>
        /// <param name="vertexCount">The number of vertices the buffer will contain.</param>
        /// <param name="usage">The resource usage specifying the type of memory the buffer should use.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the vertex declaration is null.</exception>
        protected VertexBufferImplementation(VertexDeclaration vertexDeclaration, int vertexCount, ResourceUsage usage) {
            if(vertexDeclaration == null) {
                throw new ArgumentNullException("vertexDeclaration", "Vertex declaration cannot be null.");
            }
            _vertexDecl = vertexDeclaration;
            _vertexCount = vertexCount;
            _bufferUsage = usage;
        }

        /// <summary>
        /// Creates a new instance of <see cref="VertexBufferImplementation"/>.
        /// </summary>
        /// <param name="vertexDeclaration">The vertex declaration that describes the data.</param>
        /// <param name="usage">The resource usage specifying the type of memory the buffer should use.</param>
        /// <param name="data">The interleaved data to initialize the vertex buffer with.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data or vertex declaration is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the declaration's vertex stride is not
        /// the same as the data's vertex stride.</exception>
        protected VertexBufferImplementation(VertexDeclaration vertexDeclaration, ResourceUsage usage, DataBuffer data) {
            if(data == null) {
                throw new ArgumentNullException("data", "Data cannot be null.");
            }

            if(vertexDeclaration == null) {
                throw new ArgumentNullException("vertexDeclaration", "Vertex declaration cannot be null.");
            }

            _vertexDecl = vertexDeclaration;
            _bufferUsage = usage;

            //Get the vertex count
            int totalSize = data.SizeInBytes;
            int vertexStride = vertexDeclaration.VertexStride;
            int dataStride = data.ElementSizeInBytes;

            if(vertexStride != dataStride) {
                throw new ArgumentOutOfRangeException("data", "Vertex declaration stride does not match actual data stride");
            }

            _vertexCount = totalSize / dataStride;
        }

        /// <summary>
        /// Creates a new instance of <see cref="VertexBufferImplementation"/>.
        /// </summary>
        /// <param name="vertexDeclaration">The vertex declaration that describes the data.</param>
        /// <param name="usage">The resource usage specifying the type of memory the buffer should use.</param>
        /// <param name="data">Array of databuffers to initialize the vertex buffer with, each databuffer corresponds to a single vertex element.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data or vertex declaration is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the declaration's vertex stride is not
        /// the same as the data's vertex stride, or the number of data buffers do not match the number of declaraed vertex elements, or the
        /// data buffers are not all the same length.</exception>
        protected VertexBufferImplementation(VertexDeclaration vertexDeclaration, ResourceUsage usage, params DataBuffer[] data) {
            if(data == null) {
                throw new ArgumentNullException("data", "Data cannot be null.");
            }

            if(vertexDeclaration == null) {
                throw new ArgumentNullException("vertexDeclaration", "Vertex declaration cannot be null.");
            }
            
            _vertexDecl = vertexDeclaration;
            _bufferUsage = usage;

            //Verify if the incoming vertex streams match right with the supplied vertex declaration
            VertexElement[] elems = _vertexDecl.VertexElements;
            if(elems.Length != data.Length) {
                throw new ArgumentOutOfRangeException("data", "Number of vertex streams do not match up the number of declared vertex elements.");
            }

            //Get the vertex count from the first data...we'll check if the data sizes are the same later
            _vertexCount = data[0].SizeInBytes / data[0].ElementSizeInBytes;

            int totalSizeInBytes = 0;
            int vertexStride = 0;

            for(int i = 0; i < data.Length; i++) {
                DataBuffer db = data[i];
                VertexElement element = elems[i];
                int vSizeInBytes = db.ElementSizeInBytes;
                int vCount = db.SizeInBytes / vSizeInBytes;

                if(vCount != _vertexCount) {
                    throw new ArgumentOutOfRangeException("data", "Vertex count mismatch, buffers must be of same length.");
                }
                if(vSizeInBytes != VertexDeclaration.GetVertexElementSize(element.Format)) {
                    throw new ArgumentOutOfRangeException("data", "Supplied vertex buffer element size mismatch with actual vertex element size.");
                }

                totalSizeInBytes += db.SizeInBytes;
                vertexStride += vSizeInBytes;
                db.Position = 0;
            }

            if(totalSizeInBytes != _vertexDecl.VertexStride * _vertexCount) {
                throw new ArgumentOutOfRangeException("data", "Vertex data must match the size declared for this vertex buffer!");
            }
        }


        /// <summary>
        /// Convienence method that takes an array of data buffers, each representing a vertex element (in the order
        /// declared by the vertex declaration), and writes all of the data to the vertex buffer. The buffers must match
        /// the vertex declaration as well as the byte sizes of each element and all be of the same length.
        /// </summary>
        /// <param name="data">Array of databuffers representing the vertex data.</param>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public abstract void SetInterleavedData(params DataBuffer[] data);

        /// <summary>
        /// Sets the vertex data from an array source.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array that holds the vertex data</param>
        /// <param name="startIndex">Starting index of the element in the array at which to start copying from</param>
        /// <param name="elementCount">Number of elements to copy from the array</param>
        /// <param name="offsetInBytes">Offset in bytes from the beginning of the vertex buffer to the data.</param>
        /// <param name="vertexStride">Size of an element in bytes.</param>
        /// <param name="writeOptions">Writing options for the vertex buffer. None, discard, or no overwrite.</param>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public abstract void SetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes, int vertexStride, DataWriteOptions writeOptions) where T : struct;

        /// <summary>
        /// Gets the data from the vertex buffer and copies it into specified array.
        /// </summary>
        /// <typeparam name="T">The type of data in the vertex buffer.</typeparam>
        /// <param name="data">Array to copy contents to from the vertex buffer into</param>
        /// <param name="startIndex">Index of the element in the array at each to start writing to</param>
        /// <param name="elementCount">Number of elements to copy</param>
        /// <param name="offsetInBytes">Offset in bytes from the beginning of the vertex buffer to the data.</param>
        /// <param name="vertexStride">Size of an element in bytes</param>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public abstract void GetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes, int vertexStride) where T : struct;
    }
}
